package com.ssm_crm.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssm_crm.pojo.User;
import com.ssm_crm.service.UserService;

/**
 * @author Yusei
 * 登录功能的controller
 */

@Controller
public class LoginController {
	
	@Autowired
	private UserService userService;
	
	// 跳转到登录页面
	@RequestMapping("login")
	public String toLogin(){
		return "login";
	}
	
	// 用户登录
	@RequestMapping("userLogin")
	@ResponseBody
	public User userLogin(@RequestBody User user, HttpSession session){
		// 显示post过来的数据
		System.out.println("username:" + user.getUser_code());
		System.out.println("password:" + user.getUser_password());
		// 调用Service验证登录
		User existUser = userService.userLogin(user);
		User result = new User();
		// 判断登录是否成功
		if (existUser == null) {
			result.setUser_state("0");
		}else{
			existUser.setUser_password("");
			session.setAttribute("user", existUser);
			result.setUser_state("1");
		}
		return result;
	}
	
	// 用户登出
	@RequestMapping("userLogout")
	@ResponseBody
	public String userLogout(HttpSession session){
		// 判断session中是否有用户数据
		if(session.getAttribute("user") != null){
			// 删除用户的session
			session.removeAttribute("user");
			session.invalidate();	
			return "0";
		}
		// 登出失败
		return "1";
	}
	
	
	
	
}
